package main

import (
	_ "embed"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/driver/desktop"
	hook "github.com/robotn/gohook"
	"log"
	"net/url"
	"os"
	"translate/window"
)

//go:embed myapp.ico
var icon []byte

func main() {

	themeIcon := fyne.NewStaticResource("myapp", icon)
	//创建程序
	var application = app.New()
	application.SetIcon(themeIcon)

	//创建翻译窗口
	translateWin := application.NewWindow("Translate")
	translateWin.SetIcon(themeIcon)
	translateWin.SetCloseIntercept(func() {
		translateWin.Hide()
	})

	//创建配置窗口
	configWin := application.NewWindow("Config Translate")
	configWin.SetIcon(themeIcon)
	configWin.SetCloseIntercept(func() {
		configWin.Hide()
	})

	hook.Register(hook.KeyDown, []string{"ctrl", "alt", "w"}, func(event hook.Event) {
		log.Println("触发了快捷键")
		fyne.DoAndWait(func() {
			translateWin.Show()
			log.Println("执行了")
		})
	})

	go func() {
		s := hook.Start()
		<-hook.Process(s)
	}()
	//设置系统托盘
	setSystemTray(&application, &translateWin, &configWin)

	//设置主页面
	window.SetHome(&translateWin)
	//设置配置页面
	window.SetConfig(&configWin)

	//显示并运行窗口
	translateWin.ShowAndRun()

}

func setSystemTray(app *fyne.App, homeW, configW *fyne.Window) {
	application := *app
	translateWin := *homeW
	configWin := *configW
	if deskTopApp, ok := application.(desktop.App); ok {
		deskTopApp.SetSystemTrayIcon(fyne.NewStaticResource("myapp", icon))
		deskTopApp.SetSystemTrayMenu(&fyne.Menu{
			Items: []*fyne.MenuItem{
				fyne.NewMenuItem("翻译", func() {
					//显示翻译页面
					translateWin.Show()
				}),
				fyne.NewMenuItem("配置翻译", func() {
					//显示配置页面
					configWin.Show()
				}),
				fyne.NewMenuItem("关于我", func() {
					parse, err := url.Parse("http://rocc.uno")
					if err != nil {
						log.Println("解析错误：", err.Error())
					}
					err = application.OpenURL(parse)
					if err != nil {
						log.Println("解析错误：", err.Error())
					}
				}),
				fyne.NewMenuItem("退出", func() {
					err := os.RemoveAll("./tmp")
					if err != nil {
						log.Println("删除临时文件失败：", err.Error())
					}
					application.Quit()
				}),
			},
		})
	}
}
